package com.solo.system.service.impl;

import cn.hutool.core.util.NumberUtil;
import com.solo.common.core.base.service.impl.BasicServiceImpl;
import com.solo.system.api.entity.SysDictType;
import com.solo.system.mapper.SysDictTypeMapper;
import com.solo.system.service.SysDictTypeService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Objects;

import static com.solo.common.core.utils.ServiceExceptionUtil.exception;
import static com.solo.system.api.consts.SystemCode.*;

/**
 * 字典类型Service实现类
 * @author 十一
 * @since 2023/09/22 16:25
 * 人生若只如初见，何事秋风悲画扇
 **/
@Service
@AllArgsConstructor
public class SysDictTypeServiceImpl extends BasicServiceImpl<SysDictTypeMapper, SysDictType> implements SysDictTypeService {

    private final SysDictTypeMapper sysDictTypeMapper;
    
    @Override
    public boolean create(SysDictType entity) {
        // 验证字典类型代码是否唯一
        validateCodeUnique(entity.getCode(), null);
        // 保存字典类型
        return save(entity);
    }

    @Override
    public boolean delete(Long typeId) {
        return removeById(typeId);
    }

    @Override
    public boolean update(SysDictType entity) {
        // 验证字典类型是否存在
        validateExists(entity.getTypeId());
        // 验证字典类型代码是否唯一
        validateCodeUnique(entity.getCode(), entity.getTypeId());
        // 修改字典类型
        return updateById(entity);
    }

    /**
     * 验证字典类型是否存在
     * @param typeId 类型id
     */
    void validateExists(Long typeId) {
        if (typeId == null) {
            return;
        }
        SysDictType entity = mapper.selectOneById(typeId);
        if (entity == null) {
            throw exception(DICT_TYPE_NOT_EXISTS);
        }
    }

    /**
     * 验证字典类型代码是否唯一
     * @param code 代码
     * @param typeId 类型id
     */
    void validateCodeUnique(String code, Long typeId) {
        SysDictType dictType = sysDictTypeMapper.selectByCode(code);
        if (Objects.isNull(dictType)) {
            return;
        }
        if (!NumberUtil.equals(dictType.getTypeId(), typeId)) {
            throw exception(DICT_CODE_EXISTS, code);
        }
    }

}
